package action.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import exception.Exceptions;

import util.Time;
import util.Tool;
import vo.UserBean;

public class ExcelAction{
	private String fileName;
	
	@SuppressWarnings("deprecation")
	public InputStream getInputStream() throws Exceptions {
        List list = new ArrayList();
        UserBean user1 = new UserBean(1l,"张三");
        UserBean user2 = new UserBean(2l,"李四");
        UserBean user3 = new UserBean(3l,"王五");
        list.add(user1);
        list.add(user2);
        list.add(user3);
        
        HSSFWorkbook wb = new HSSFWorkbook();
        //添加一个sheet
        HSSFSheet sheet = wb.createSheet("学生表一");
        //sheet中添加表头第0行
        HSSFRow row = sheet.createRow((int)0);
        //创建单元格，并设置值表头  设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //创建一个居中格式
        
        HSSFCell cell = null;
        
        cell = row.createCell((short)0);
        cell.setCellValue("学号");
        cell.setCellStyle(style);
        
        cell = row.createCell((short)1);
        cell.setCellValue("姓名");
        cell.setCellStyle(style);
        
        cell = row.createCell((short)2);
        cell.setCellValue("日期");
        cell.setCellStyle(style);
    
        //将list写入
        int listSize=list.size();
        for(int i=0;i<listSize;i++){
            row = sheet.createRow(i+1);
            UserBean stu = (UserBean) list.get(i);
            //把list中的值写入到对应的列中
            row.createCell((short)0).setCellValue(stu.getUserId());
            row.createCell((short)1).setCellValue(stu.getUserName());
            row.createCell((short)2).setCellValue(Time.Timestamp2DateString(Time.CurrentTimestamp()));
        }

		//下载文件名
        fileName=Tool.toChinese("这是个中文名.xls");
        //输出下载
		ByteArrayOutputStream baos = new ByteArrayOutputStream();  
		try {
			wb.write(baos);
		} catch (IOException e) {
			e.printStackTrace();
		}
        byte[] ba = baos.toByteArray();  
        ByteArrayInputStream bais = new ByteArrayInputStream(ba);
        return bais;
	}
	
	public String execute(){
		System.out.println("------------");
		return "success";
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}
